<template>
  <div>
    <!-- <Modal
      v-model="visible"
      :title="isEdit ? '编辑账号' : '添加账号'"
      @on-ok="handleSubmit"
      @on-cancel="handleCancel"
    > -->
	<Modal
	  v-model="visible"
	  :title="isEdit ? '编辑账号' : '添加账号'"
	  @on-ok="handleSubmit"
	  @on-cancel="handleCancel"
	>
      <Form ref="form" :model="formData" :rules="rules" label-width="80">
        <FormItem label="账号" prop="account">
          <Input v-model="formData.account" :disabled="isEdit" @input="handleAccountInput"></Input>
        </FormItem>

        <FormItem label="密码" prop="password">
          <Input type="password" v-model="formData.password" password />
        </FormItem>

        <FormItem label="昵称" prop="real_name">
          <Input v-model="formData.real_name" />
        </FormItem>

        <FormItem label="手机号" prop="phone">
          <Input v-model="formData.phone" />
        </FormItem>

        <FormItem label="状态" prop="status">
          <Select v-model="formData.status"  :label-in-value="false"  @change="val => console.log('status:', val, typeof val)">
            <Option :value="1">启用</Option>
            <Option :value="0">禁用</Option>
          </Select>
        </FormItem>

        <FormItem label="角色" prop="roles">
          <Select v-model="formData.roles" multiple>
            <Option
              v-for="role in allRoles"
              :key="role.value"
              :value="role.value"
            >
              {{ role.label }}
            </Option>
          </Select>
        </FormItem>
      </Form>
	   <!-- 自定义底部按钮 -->
	    <div slot="footer" style="text-align: right;">
	      <Button @click="handleCancel">取消</Button>
	      <Button type="primary" @click="handleSubmit">确定</Button>
	    </div>
    </Modal>
  </div>
</template>

<script>
	import { createAdminApi } from '@/api/systemAdmin';
export default {
  name: "AccountModal",
  props: {
    visible: Boolean,
    data: Object, // 编辑时传入的数据
    allRoles: {
      type: Array,
      default: () => ["管理员", "运营", "财务", "客服"], // 所有角色
    },
  },
  data() {
    return {
		localVisible: false,
      formData: {
        id: null,
        account: "",
        password: "",
        real_name: "",
        phone: "",
		pwd:"",
        status: 1,
        roles: [],
      },
      rules: {
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        real_name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" },{
			pattern: /^1[3-9]\d{9}$/,
			message: "手机号格式不正确",
			trigger: "blur"
		}],
		 status: [
		    {
		      validator: (rule, value, callback) => {
		        if (value === 0 || value === 1) {
		          callback(); // 验证通过
		        } else {
		          callback(new Error("请选择状态"));
		        }
		      },
		      trigger: "change",
		    },
		  ],
        roles: [{ required: true, type: 'array', min: 1, message: "请选择角色", trigger: "change" }],
      },
    };
  },
  computed: {
    isEdit() {
      return this.data && this.data.id;
    },
  },
  watch: {
    visible(val) {
        if (val) {
          this.initForm(); // 弹窗打开时初始化表单
        }
      },
      data: {
        handler(val) {
          if (this.visible) this.initForm(); // 数据变化时同步更新
        },
        deep: true
      }
  },
  methods: {
	  handleAccountInput(value) {
		  setTimeout(()=>{
				// 移除中文字符（包括全角字符）
			      const filteredValue = value.replace(/[\u4e00-\u9fa5\uFF00-\uFFEF]/g, '');
			      
			      // 更新模型值（确保光标位置正确）
			      if (filteredValue !== value) {
			        this.formData.account = filteredValue;
			      }
		  },0)
	      
	    },
    initForm() {
      if (this.isEdit) {
        const { id, account,pwd, real_name, phone, status, roles } = this.data;
		console.log("===========",roles)
        this.formData = {
          id,
          account,
          password: pwd, // 密码不回显
          real_name,
          phone,
          status,
          roles: (roles || []).map(r => r.toString()),
        };
      } else {
        this.formData = {
          id: null,
          account: "",
          password: "",
          real_name: "",
          phone: "",
          status: 1,
          roles: [],
        };
      }
    },
	handleSubmit() {
		this.formData.pwd = this.formData.password
		this.$refs.form.validate((valid) => {
		  if (valid) {
		    createAdminApi(this.formData)
		      .then((res) => {
				  console.log('res.msg',res.msg)
		        this.$Message.success(res.msg)
				// 通知父组件提交成功
				this.$emit("submit")
				if (this.$refs.form) {
				    this.$refs.form.resetFields();
				}
		        this.formInline.checked_menus = []
		      })
		      .catch((res) => {
		        this.$Message.error(res.msg)
		      })
		  } else {
		    this.$Message.error('请填写必填项');
		  }
		});
	   
	},

	handleCancel() {
	  if (this.$refs.form) {
	    this.$refs.form.resetFields(); // 清空校验 + 重置表单字段
	  }
	  this.$emit("cancel"); //通知父组件关闭弹窗
	}
  },
};
</script>
